package cn.airfei.aircore.core.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @description: 自动填充数据
 * @author: air
 * @create: 2019-06-18 17:22
 **/
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    private Boolean deletedDefault = false;

    // 添加数据时
    private String[] insertFieldForDate = {"createTime", "updateTime", "createDate", "updateDate", "EXCHANGE_DATE", "UPDATED_DATE", "CREATED_DATE", "createdAt", "updatedAt"};

    // 更新数据时
    private String[] updateFieldForDate = {"updateTime", "UPDATED_DATE", "updatedAt", "updateDate"};

    @Override
    public void insertFill(MetaObject metaObject) {

        // 设置自动插入时间
        for (int i = 0; i < insertFieldForDate.length; i++) {
            setFieldForDate(insertFieldForDate[i], metaObject);
        }

        // 删除字段
        if (hasValue(metaObject.getGetterNames(), "deleted")) {
            Object deleted = getFieldValByName("deleted", metaObject);
            if (deleted == null) {
                setFieldValByName("deleted", deletedDefault, metaObject);
            }
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 设置更新时插入时间
        for (int i = 0; i < updateFieldForDate.length; i++) {
            setFieldForDate(updateFieldForDate[i], metaObject);
        }
    }


    /**
     * 设置时间类型
     *
     * @param field
     * @param metaObject
     */
    private void setFieldForDate(String field, MetaObject metaObject) {
        if (hasValue(metaObject.getGetterNames(), field)) {
            Object UPDATED_DATE = getFieldValByName(field, metaObject);
            if (UPDATED_DATE == null) {
                this.setFieldValByName(field, LocalDateTime.now(), metaObject);
            }
        }
    }


    /**
     * 判断字符串数组中是否有某个值
     *
     * @param arr
     * @param value
     * @return
     */
    private static boolean hasValue(String[] arr, String value) {
        return Arrays.asList(arr).contains(value);
    }
}
